<template>
  <el-dialog :title="!dataForm.id ? '新增' : '修改'" :close-on-click-modal="false" :visible.sync="visible">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()" label-width="80px">
      <el-form-item label="门店名称" prop="storeName">
        <el-input v-model="dataForm.storeName" placeholder="请输入门店名称"></el-input>
      </el-form-item>
      <el-form-item label="地址" prop="address">
        <el-button v-show="true" @click="queryLocation" style="width: 100%;text-align: left;color: #bbb;font-weight: 400;padding: 10px 15px;">{{dataForm.address||'请输入地址'}}</el-button>
        <el-input v-show="false" v-model="dataForm.address" placeholder="请输入地址" readonly></el-input>
      </el-form-item>
      <el-form-item label="电话" prop="telePhone">
        <el-input v-model="dataForm.telePhone" placeholder="请输入手机号"></el-input>
      </el-form-item>
      <el-form-item label="账号" prop="account">
        <el-input v-model="dataForm.account" placeholder="请输入账号"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="dataForm.password" placeholder="请输入密码"></el-input>
      </el-form-item>
      <el-form-item label="经度" prop="mapX" v-show="false">
        <el-input v-model="dataForm.mapX" placeholder="请输入经度" readonly></el-input>
      </el-form-item>
      <el-form-item label="纬度" prop="mapY" v-show="false">
        <el-input v-model="dataForm.mapY" placeholder="请输入纬度" readonly></el-input>
      </el-form-item>
      <el-form-item label="门店信息" prop="businessCardImg">
        <el-upload class="upload-demo" :action="upload.url + '/hd-api/upload/file'" :headers="headers" :on-remove="handleRemove" :file-list="dataForm.fileList" :on-success="handleSuccess" list-type="picture-card">
          <el-button size="small" type="text">门店信息上传</el-button>
          <div slot="tip" class="el-upload__tip">
            只能上传jpg/png文件，且不超过500kb
          </div>
        </el-upload>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
    <el-dialog width="800px" title="选择位置" :visible.sync="innerVisible" :before-close="handleClose" append-to-body>
      <section id="LocationMap" style="width:100%;height:480px;"></section>
    </el-dialog>
  </el-dialog>
</template>

<script>
  import Vue from "vue";
  export default {
    data() {
      return {
        qqMapServer: null,
        innerVisible: false,
        upload: {
          url: "https://shanxihongdi.com",
        },
        headers: {
          token: Vue.cookie.get("token"),
        },
        visible: false,
        dataForm: {
          id: 0,
          storeName: "",
          telePhone: "",
          address: "",
          account: "",
          password: "",
          mapX: 0,
          mapY: 0,
          fileList: [],
          businessCardImg: "",
          status: "",
        },
        dataRule: {
          storeName: [{
            required: true,
            message: "门店名称不能为空",
            trigger: "blur",
          }, ],
          telePhone: [{
            required: true,
            message: "电话不能为空",
            trigger: "blur",
          }, ],
          address: [{
            required: true,
            message: "地址不能为空",
            trigger: "blur",
          }, ],
          account: [{
            required: true,
            message: "账号不能为空",
            trigger: "blur",
          }, ],
          password: [{
            required: true,
            message: "密码不能为空",
            trigger: "blur",
          }, ],
          mapX: [{
            required: true,
            message: "经度不能为空",
            trigger: "blur",
          }, ],
          mapY: [{
            required: true,
            message: "纬度不能为空",
            trigger: "blur",
          }, ],
          status: [{
            required: true,
            message: "状态 0禁用 1正常不能为空",
            trigger: "blur",
          }, ],
        },
      };
    },
    methods: {
      queryLocation() {
        const _this = this;
        _this.innerVisible = true;
        _this.$nextTick(() => {
          _this.initMap();
        })
      },
      initMap() {
        const _this = this;
        // 定义地图中心点坐标
        var center = new window.TMap.LatLng(34.269928836203, 108.947160183469)
        // 定义map变量，调用 TMap.Map() 构造函数创建地图
        _this.qqMapServer = new window.TMap.Map(document.getElementById('LocationMap'), {
          center: center, // 设置地图中心点坐标
          zoom: 12.8, // 设置地图缩放级别
          pitch: 0, // 设置俯仰角
          rotation: 0 // 设置地图旋转角度
        })
        //定义事件处理方法
        var clickHandler = function(evt) {
          var lat = evt.latLng.getLat().toFixed(12);
          var lng = evt.latLng.getLng().toFixed(12);
          console.log("您点击的的坐标是：" + lat + "," + lng + ", [" + (evt.poi && evt.poi.name || '') + "]");
          _this.$jsonp('https://apis.map.qq.com/ws/geocoder/v1', {
            location: lat + "," + lng,
            key: "ZWZBZ-Q7LWF-OM3JC-JFSUO-HW7MJ-FKFLH",
            get_poi: 1,
            output: 'jsonp'
          }).then(res => {
            _this.dataForm.address = res.result.address + (evt.poi && evt.poi.name || '');
            _this.dataForm.mapX = lng;
            _this.dataForm.mapY = lat;
            _this.handleClose();
          })
        }
        //Map实例创建后，通过on方法绑定点击事件
        _this.qqMapServer.on("click", clickHandler)
      },
      handleClose() {
        const _this = this;
        _this.qqMapServer.destroy();
        _this.innerVisible = false;
      },
      onInputBlur() {
        const _this = this;
        const myGeo = new BMap.Geocoder();
        // 将地址解析结果显示在地图上，并调整地图视野
        myGeo.getPoint(_this.dataForm.address, function(point) {
          _this.dataForm.mapX = point.lng;
          _this.dataForm.mapY = point.lat;
          console.log(point, _this.dataForm);
        });
      },
      init(id) {
        this.dataForm.id = id || 0;
        this.visible = true;
        this.$nextTick(() => {
          this.$refs["dataForm"].resetFields();
          if (this.dataForm.id) {
            this.$http({
              url: this.$http.adornUrl(
                `/activity/store/info/${this.dataForm.id}`
              ),
              method: "get",
              params: this.$http.adornParams(),
            }).then(({ data }) => {
              if (data && data.code === 0) {
                this.dataForm.fileList = [{
                  // name: data.store.businessCardImg
                  //     .split("/")
                  //     .splice(-1)[0],
                  // url:
                  //     this.upload.url +
                  //     data.store.businessCardImg,
                }, ];
                this.dataForm.storeName = data.store.storeName;
                this.dataForm.telePhone = data.store.telePhone;
                this.dataForm.address = data.store.address;
                this.dataForm.account = data.store.account;
                this.dataForm.password = data.store.password;
                this.dataForm.status = data.store.status;
                this.dataForm.createTime = data.store.createTime;
                this.dataForm.mapX = data.store.mapX;
                this.dataForm.mapY = data.store.mapY;
              }
            });
          }
        });
      },
      // 表单提交
      dataFormSubmit() {
        this.$refs["dataForm"].validate((valid) => {
          if (valid) {
            this.$http({
              url: this.$http.adornUrl(
                `/activity/store/${
                    !this.dataForm.id ? "save" : "update"
                }`
              ),
              method: "post",
              data: this.$http.adornData({
                id: this.dataForm.id || undefined,
                storeName: this.dataForm.storeName,
                telePhone: this.dataForm.telePhone,
                address: this.dataForm.address,
                account: this.dataForm.account,
                password: this.dataForm.password,
                status: this.dataForm.status,
                mapX: this.dataForm.mapX,
                mapY: this.dataForm.mapY,
                createTime: this.dataForm.createTime,
                businessCardImg: this.dataForm.businessCardImg,
              }),
            }).then(({ data }) => {
              if (data && data.code === 0) {
                this.$message({
                  message: "操作成功",
                  type: "success",
                  duration: 1500,
                  onClose: () => {
                    this.visible = false;
                    this.$emit("refreshDataList");
                  },
                });
              } else {
                this.$message.error(data.msg);
              }
            });
          }
        });
      },
      handleRemove(file, fileList) {
        console.log(file, fileList);
      },
      handleSuccess(file) {
        if (file.code === 0) {
          this.dataForm.businessCardImg = file.msg;
        }
      },
    },
  };
</script>
